package s12_经典算法.a3_KMP算法;

/**
 * Created by 西瓜瓜
 * Date :2022/2/27
 * Description :
 * Version :1.0
 * 暴力匹配算法
 */
public class ViolenceMatch {

    public static void main(String[] args) {

        String str1 = "dabsvgsabklgjsakbkesagjsabrkgbksabask f kasdgfhsakuhfkl;as efl;hsa klegbsabkvl assaeufhsaef as";
        String str2 = "saef as";
        System.out.println(new ViolenceMatch().violenceMatch(str1, str2));

    }

    /**
     * 暴力匹配算法实现
     *
     * @param str1 原始字符串
     * @param str2 待匹配字符串
     * @return
     */
    public int violenceMatch(String str1, String str2) {
        char[] c1 = str1.toCharArray();
        char[] c2 = str2.toCharArray();

        int s1Len = c1.length;
        int s2Len = c2.length;

        int i = 0; // 指向s1
        int j = 0; // 指向s2

        while (i < s1Len && j < s2Len) {
            if(c1[i] == c2[j]) {
                // 匹配成功
                i++;
                j++;
            } else {
                // 没有匹配成功
                i = i - (j - 1);
                j = 0;
            }
        }

        // 判断是否匹配成功
        if(j == s2Len) {
            return i - j;
        } else {
            return -1;
        }

    }
}
